// dep on Util.js
var Timer = {
	/* your time is up */

	/* how often in ms do tasks get run? */
	delay : 100, 

	tick: 0, 	

	timerTasks : [],

	interval : '',

	asTimeGoesBy : function() {
		Timer.tick++;
		var alive = [];

		for ( var i = 0 ; i < Timer.timerTasks.length ; i++ ){
			var task = Timer.timerTasks[ i ];
			try {
				if ( task.run( Timer.tick ) ) {
					alive.push( task );
				} else {
					if( task.done ) {
						task.done( Timer.tick );
					}
				}
			} catch ( exception ) {
				Util.log( task + ' -> ' + exception ); 
			}
		}
		if ( 0 == alive.length ) {
			Timer.clearTasks();
		} else {
			Timer.timerTasks = alive;
		}
	},

	addTask : function( task ) {
		Timer.timerTasks.push( task );
		if ( !Timer.interval ) {
			Timer.tick = 0;
			Timer.interval = setInterval( 'Timer.asTimeGoesBy()', Timer.delay );
		}
	},

	invalidArrayIndex : -1,

	find : function( needle, haystack ) {
		var index = Timer.invalidArrayIndex;
		for ( var i = 0 ; i < haystack.length ; i++ ) {
			if ( needle == haystack[ i ] ) {
				index = i;
				break;
			}
		}
		return index;
	},

	removeTask : function( task ) {
		Timer.timerTasks = Util.removeFromArray( Timer.timerTasks, task );
	},

	clearTasks : function() {
		if ( Timer.interval ) {
			clearInterval( Timer.interval );
		}
		Timer.tick = 0;
		Timer.interval = Timer.unset;
		Timer.timerTasks = [];
	},

	noop : function() {}

};
